package com.example.finalassignment.common;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储到ThreadLocal里上下文
 */

@Component
public class ThreadContext {

    public static final ThreadLocal<Map<String, String>> threadLocal = new ThreadLocal<>();

    /**
     * 设置map
     */
    public static void setThreadLocalValue() {
        Map<String, String> map = new ConcurrentHashMap<>();
        threadLocal.set(map);
    }

    /**
     * 获取ThreadLocal里的内容
     */
    private static Map<String, String> getContext() {
        return threadLocal.get();
    }

    /**
     * 根据key获取值
     */
    public static String getValue(String key) {
        return getContext().get(key);
    }

    /**
     * 传入的key存不存在
     */
    public static boolean containsKey(String key) {
        return getContext().containsKey(key);
    }

    /**
     * 保存
     */
    public static void setKeyAndValue(String key, String value) {
        getContext().put(key, value);
    }

    /**
     * 获取token
     */
    public static String getToken() {
        return getContext().get("token");
    }

    /**
     * 获取userId
     */
    public static String getUserId() {
        return getContext().get("userId");
    }
}
